//
//  SingleColumnPickerView.m
//  ZZmetro
//
//  Created by 一介布衣 on 2020/6/17.
//  Copyright © 2020 一介布衣. All rights reserved.
//

#import "SingleColumnDataPickerView.h"
#import "PickerViewLabel.h"

@interface SingleColumnDataPickerView()

@end


@implementation SingleColumnDataPickerView

// 步骤 1：重写initWithFrame:方法，创建子控件并 - 添加
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.delegate = self;
        self.dataSource = self;
        self.showsSelectionIndicator = YES;
        [self reloadAllComponents];
        self.frame = CGRectMake(0, 0, SCREEN_WIDTH, 248);
    }
    return self;
}

// 步骤 2：重写layoutSubviews，子控件设置frame
- (void)layoutSubviews {
    [super layoutSubviews];
}

-(void)setPickData:(NSArray *) data {
    _pickData = data;
    if (data && data.count > 0) {
        _pickedData = data[0];
    }
}

#pragma -- UIPickerViewDataSource, UIPickerViewDelegate
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return _pickData.count;
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    NSString* s = [_pickData objectAtIndex:row];
    return s;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    //NSLog([NSString stringWithFormat:@"selected:%i:", component]);
    if(row < 0){
        row = 0;
    }
    NSString* val = self.pickData[row];
    NSIndexPath* index = [NSIndexPath indexPathForRow:row inSection:0];
    
    self.pickedData = val;
    self.pickedIndex = index;
}

-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return 36;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    //当2行时，容易变形,所以指定宽度
    return 120;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    //设置分割线的颜色
    for(UIView *singleLine in pickerView.subviews){
        if (singleLine.frame.size.height < 1){
            singleLine.backgroundColor = [UIColor colorWithRed:0.85 green:0.85 blue:0.85 alpha:1];
        }
    }
    //设置文字的属性
    UILabel *label = [PickerViewLabel new];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:16.0];
    label.textColor = UIColor.blackColor;
    
    label.text = self.pickData[row];
    return label;
}

@end
